package org.androbuzz;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
import android.util.Log;


public class AndroBuzzAccount{
	
	private String TAG = "Androbuzz.AccountManager";
	private String Username;
	private Context BaseContext;
	private AndroBuzzDbAdapter mDb;
	private AndroBuzzOauthClient mOauth;
	
	
	public AndroBuzzAccount(Context context) {
		BaseContext = context;
		
		mDb = new AndroBuzzDbAdapter(BaseContext);
		mDb.open();
	}
    
	/**
	 * Initialize Account by saving Google login and
	 * request authorization against Google OAuth server
	 */
	public void initialize() {
		if(getUsername().length() > 0 && !getUsername().equals("androbuzz")) {
			save();
			SharedPreferences config = PreferenceManager.getDefaultSharedPreferences(BaseContext);
			Editor editor = config.edit();
			editor.putString("AndroBuzzLoginId", getUsername());
			editor.commit();
			Log.d(TAG, "Account saved");
		}
		
		if(!(mDb.getToken().length() > 0)) {
			Log.d(TAG, "Requesting Authorization Token");
			mOauth = new AndroBuzzOauthClient(BaseContext);
			mOauth.requestAuthorization();
		}
		mDb.close();
	}
	
	/**
	 * Fetch Registered Google Account from AccountManager API
	 * 
	 * @return	current registered account (only one)
	 */
	public String getUsername() {
		SharedPreferences config = PreferenceManager.getDefaultSharedPreferences(BaseContext);
		
		final AccountManager accountManager = AccountManager.get(BaseContext);
		final Account[] accounts = accountManager.getAccounts();
		final int accountsCount = accounts.length;
		
		Account login = null;
		// TODO: maybe pull the login from DB instead?
		Username = config.getString("AndroBuzzLoginId", "");
		
		// Double check on startup and empty prefs that we don't have a login
		// *** This can be remove on first release ***
		if(accountsCount == 0 /**&& Username.equals("") == false*/){
			// set default account name to androbuzz if no Google account has been registered
			// TODO: pop-up a notification about missing login account instead
			Log.d(TAG, "****** No Registered Google Account found! :(");
			Username = "androbuzz";
		}
		else{
			// Check if we have a registered value from AndroBuzz Preference
			// otherwise grab it from Android.AccountManager
			if (Username.length() > 0) {
				
				return Username;
			}
			else {
				for (int i=0; i<accountsCount; i++){
				login = accounts[i];
			    
				Log.d(TAG, " Found Login Id: " + login);
				Log.d(TAG, "Found Name: " + login.name + "\nFound Type: " + login.type);
				
					// TODO: Parse and display for more than one account
					// Check that we do deal with an Google's account
					// and stop on first one we found for now.
					if (login.type.equals("com.google")) {
						Username = login.name.replace("@gmail.com", "");
						Log.d(TAG, "Found username: " + Username);
						break;
					}
					else {
						// TODO: notify and ask about available accounts list view
						Log.d("AndroBuzz.Acc", "Unable to get Account data from: " + login.type);
						Username = "androbuzz";
					}
				}
			}
		}

		return Username;
	}
	
	/**
	 * Save current Google Account login
	 */
	public void save() {
		// TODO: save fetched login into Database
		if (!(mDb == null)) {
			mDb.addProfile(getUsername(), true);
			//mDb.close();
		}
	}

}
